#include "myview.h"

#include <QApplication>
#include <QCursor>
#include <QDebug>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <QGraphicsEllipseItem>

const int radius = 10;

MyView::MyView(QWidget *parent) :
    QGraphicsView(parent),
    m_mode(BrushMode),
    m_lock(NoLock)
{
	setScene(new QGraphicsScene(0, 0, 480, 320, this));
}

MyView::LockState MyView::lockState()
{
	return m_lock;
}

void MyView::setMode(int mode)
{
    m_mode = static_cast<Mode>(mode);
}

void MyView::setLockState(LockState lock)
{
	m_lock = lock;
}

void MyView::paint(int mode, QPoint point, bool noEmit)
{
    Mode old = m_mode;
    m_mode = static_cast<Mode>(mode);
	paint(point, noEmit);
	m_mode = old;
}

void MyView::onSceneStateNeeded(QTcpSocket *s)
{
	QList<QPair<int, QPoint> > list;

	foreach(QGraphicsItem *item, scene()->items(Qt::AscendingOrder))
	{
		QGraphicsEllipseItem *i = dynamic_cast<QGraphicsEllipseItem *>(item);
		QPair<int, QPoint> pair;
		pair.first = (i->brush().color() == Qt::yellow) ? BrushMode : RubberyMode;
		pair.second = QPoint(i->rect().x() - radius, i->rect().y() - radius);
		list.append(pair);
	}

	emit sceneState(s, list);
}

void MyView::enterEvent(QEvent *event)
{
    switch(m_mode)
    {
    case BrushMode:

        break;

    case RubberyMode:

        break;
    }
    QGraphicsView::enterEvent(event);
}

void MyView::leaveEvent(QEvent *event)
{
    QGraphicsView::leaveEvent(event);
}

void MyView::mousePressEvent(QMouseEvent *event)
{
	if ( m_lock == NoLock || m_lock == MyLock )
	{
		if ( event->button() & Qt::LeftButton )
		{
			paint(QPoint(event->pos().x()-radius, event->pos().y()-radius));
		}
	}
}

void MyView::mouseMoveEvent(QMouseEvent *event)
{
	if ( m_lock == NoLock || m_lock == MyLock )
	{
		if ( event->buttons() & Qt::LeftButton )
		{
			paint(QPoint(event->pos().x()-radius, event->pos().y()-radius));
		}
	}
}

void MyView::paint(QPoint point, bool noEmit)
{
    switch(m_mode)
    {
    case BrushMode:
    {
		scene()->addEllipse(point.x(), point.y(),
							2*radius, 2*radius, QPen(Qt::yellow), QBrush(Qt::yellow));
        break;
    }
    case RubberyMode:
		scene()->addEllipse(point.x(), point.y(),
							2*radius, 2*radius, QPen(Qt::white), QBrush(Qt::white));
        break;
    }
	if ( ! noEmit )
		emit painted(m_mode, QPoint(point.x(), point.y()));
}
